package handler

import (
	"github.com/eatmoreapple/openwechat"
	"log"
	"wechat/gpt/client/conf"
	"wechat/gpt/client/session"
)

const (

	// 用户消息
	user = 1

	// 群消息
	group = 2
)

var (

	// 消息处理器映射器
	handlerMap map[int]IMessageHandler

	// 用户session
	userSession session.IUserSession
)

func init() {

	// 初始化处理策略
	handlerMap = make(map[int]IMessageHandler)
	handlerMap[user] = NewUserMessageHandler()
	handlerMap[group] = NewGroupMessageHandler()

	// 初始化session对象
	userSession = session.NewUserSession()
}

type IMessageHandler interface {
	handle(message *openwechat.Message) error
	replyText(message *openwechat.Message) error
}

func Handler(msg *openwechat.Message) {

	// 记录收到的消息
	log.Printf("received msg : %v\n", msg.Content)

	// 处理群消息
	if msg.IsSendByGroup() {
		handlerMap[group].handle(msg)
		return
	}

	// TODO: 好友申请
	if msg.IsFriendAdd() {
		if conf.GetConfig().AutoPass {
			_, err := msg.Agree("你好，我是ChatGPT微信机器人，你可以向我提问")
			if err != nil {
				log.Fatalf("add friend agree error : %v", err)
				return
			}
		}
		return
	}

	// 私聊
	handlerMap[user].handle(msg)
}

func QrCodeCallback(uuid string) {
	openwechat.PrintlnQrcodeUrl(uuid)
}
